<?php
include '../login/db_connect.php';
include '../login/functions.php';
sec_session_start ();
if (isset ( $_COOKIE ['login_string'] )) {
	$login_string = $_COOKIE ['login_string'];
	$username = $_COOKIE ['username'];
	$user_id = $_COOKIE ['user_id'];

	$_SESSION ['user_id'] = $user_id;
	$_SESSION ['login_string'] = $login_string;
	$_SESSION ['username'] = $username;
}


if(isset($_POST['destinatario'], $_POST['oggetto'], $_POST['messaggio'])){
	$query_get_box="SELECT id_box FROM messagebox WHERE account='".$_POST['destinatario']."'";
	if ($result = $mysqli->query ( $query_get_box )) {
		while ( $row = $result->fetch_assoc () ) {
			$box = $row ['id_box'];
		}
		$result->free ();
	}
	else echo "Query fallita.";
	
	$query_send_message = "INSERT INTO `message` (`messagebox`, `id_message`, `send_date`, `sender`, `receiver`, `subject`, `content`, `checked`) VALUES ('".$box."', 'NULL', CURRENT_TIMESTAMP, '".$user_id."', '".$_POST['destinatario']."', '".$_POST['oggetto']."', '".$_POST['messaggio']."', '0');";
	if ($result = $mysqli->query ( $query_send_message )) {
		
		//header("Location: message2.php");
	}
	else echo "Query non eseguita!";
	
	
	
	
	
	
	
	//MANDIAMO LA MAIL VERA E PROPRIA
	$query_email_mitt = "SELECT email FROM members WHERE id='".$user_id."'";
	if ($result = $mysqli->query ( $query_email_mitt )) {
		while ( $row = $result->fetch_assoc () ) {
			$mittente = $row ['email'];
		}
		$result->free ();
	}
	else echo "Query mittente fallita.";
	
	$query_email_dest = "SELECT email FROM members WHERE id='".$_POST['destinatario']."'";
	if ($result = $mysqli->query ( $query_email_dest )) {
		while ( $row = $result->fetch_assoc () ) {
			$destinatario = $row ['email'];
		}
		$result->free ();
	}
	else echo "Query destinatario fallita.";
	
	echo $mittente."....".$destinatario;
	if(mail($destinatario, $_POST['oggetto'], $_POST['messaggio']))
	echo "Email inviata.";
	else echo "Email non inviata.";
	
	if(mail("peppethebest92@hotmail.it", "Test", "Test se funziona."))
		echo "Email inviata.";
	else echo "Email non inviata.";
	
	
	
}

?>